<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" plain @click="addroledialog">添加新闻</el-button>
    </div>
    <div class="filter-container">
      <el-input clearable @keyup.enter.native="handleFilter" style="width: 150px;" class="filter-item" placeholder="新闻标题" v-model="listQuery.title">
      </el-input>
      <el-button clearable size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column label="图片" align="center" width="140">
        <template slot-scope="scope">
          <img :src="scope.row.img" width="100" height="100">
        </template>
      </el-table-column>
      <el-table-column align="center" label='新闻标题'>
        <template slot-scope="scope">
          {{scope.row.title}}
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.typeName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否发布" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.hasRelease === true">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label='真实浏览量' width="100">
        <template slot-scope="scope">
          {{scope.row.initialViews}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='APP展示浏览量' width="120">
        <template slot-scope="scope">
          {{scope.row.views}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='排序' width="100">
        <template slot-scope="scope">
          {{scope.row.sort}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="bianji(scope.row,scope.$index)" plain>编辑</el-button>
          <el-button type="danger" size="mini" @click="shanchu(scope.row, scope.$index)" plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--编辑表单弹窗-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="formsrules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='margin-left:20px; margin-right: 20px;'>
        <el-form-item label="新闻标题：" prop="title">
          <el-input type="text" v-model="temp.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻简介：" prop="introduction">
          <el-input type="textarea"
                    v-model="temp.introduction"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="图片上传：" prop="img">
          <el-upload
            class="upload-demo"
            action="https://admin.ajhbw.cn/util/upload"
            :file-list="fileList"
            :on-success="handlePreviewsucc"
            :limit="1"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属类型：" prop="typeId">
          <el-select v-model="temp.typeId" placeholder="请选择" style="width: 175px;">
            <el-option v-for="item in typeList" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="初始浏览量：">
          <el-input type="text" v-model="temp.initialViews" style="width: 260px;"></el-input>
        </el-form-item>
        <el-form-item label="是否发布：">
          <el-select v-model="temp.hasRelease" placeholder="请选择" style="width: 175px;">
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序：">
          <el-input type="text" v-model="temp.sort" style="width: 260px;"></el-input>
        </el-form-item>
        <el-form-item label="编辑：" prop="content">
          <div class="myEditor">
            <editor ref="myTextEditor"
                    :fileName="'myFile'"
                    :uploadUrl="uploadUrl"
                    v-model="temp.content"></editor>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addrole">确 定</el-button>
        <el-button v-else type="primary" @click="sureEdit">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑表单弹窗END-->

    <!--分页-->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30,50]"
                     :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!--分页END-->
  </div>
</template>

<script>
  import { getList, getTypeList, addroles, sureEdit, shanchu } from '@/api/news/newsList'
  import editor from '@/components/Quilleditor/Quilleditor.vue'

  export default {
    data() {
      return {
        list: null,
        listLoading: true,
        total: null,
        listQuery: {
          id: undefined,
          title: ''
        },
        temp: {
          uuid: undefined,
          title: '',
          introduction: '',
          img: undefined,
          typeId: '',
          initialViews: '',
          hasRelease: true,
          content: ''
        },
        dialogStatus: '',
        typeList: undefined,
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogFormVisible: false,
        formsrules: {
          title: [{ required: true, message: '请输入', trigger: 'blur' }],
          img: [{ required: true, message: '请选择', trigger: 'change' }],
          typeId: [{ required: true, message: '请选择', trigger: 'change' }],
          content: [{ required: true, message: '请填写', trigger: 'change' }],
          introduction: [{ required: true, message: '请输入', trigger: 'blur' }]
        },
        fileList: [],
        uploadUrl: 'https://admin.ajhbw.cn/util/upload'
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          normal: '正常',
          disble: '停止'
        }
        return statusMap[status]
      }
    },
    created() {
      this.fetchData()
      this.getTypeList()
    },
    components: {
      editor
    },
    methods: {
      // 获取列表
      fetchData() {
        this.listLoading = true
        getList(this.listQuery).then(response => {
          this.list = response.data.content
          this.total = response.data.totalElements
          this.listQuery.size = response.data.size
          this.listLoading = false
        })
      },
      getTypeList() {
        getTypeList().then(response => {
          this.typeList = response.data
        })
      },
      handleFilter() {
        this.fetchData()
      },
      addroledialog() {
        this.resetTemp()
        this.fileList = []
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      resetTemp() {
        this.temp = {
          uuid: undefined,
          title: '',
          img: undefined,
          typeId: '',
          initialViews: '',
          hasRelease: true,
          content: ''
        }
      },
      addrole() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addroles(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              location.reload()
            })
          }
        })
      },
      bianji(row) {
        this.temp = Object.assign({}, row)
        this.temp.recommend = row.recommend
        this.fileList = [{ name: '', url: this.temp.img }]
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      sureEdit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const temData = Object.assign({}, this.temp)
            sureEdit(temData).then(response => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      shanchu(row) {
        this.$confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          shanchu(row.uuid).then(() => {
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.fetchData()
      },
      handlePreviewsucc(res, file) {
        this.temp.img = res.data[0]
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .filter-container{
    padding-bottom: 10px;
  }
  .area-select .el-select{
    margin-left: 0;
  }
  .myEditor{
    height: 400px;
  }
</style>
